#include "tabpage.h"
#include "myspaces.h"
#include <QPlastiqueStyle>

tabPage::tabPage(QTabWidget *parent) :
    QMainWindow(parent),
    m_splitter(new QSplitter(this)),
    Browser(new myWebView),
    m_inspector(new myWebInspector()),
    toolBar(new QToolBar),
    goHomeButton(new QToolButton),
    inspectorButton(new QToolButton()),
    mainMenuButton(new QToolButton),
    locationEdit(new QLineEdit),
    mainMenu(new QMenu),
    title(new QString("mySpaces")),
    showInspector(false),
    progress(0),
    forward(new QToolButton),
    back(new QToolButton),
    ReloadStop(new QToolButton)
{
    setWindowOpacity(0);
    // Loading jQuery
    QFile file(QLatin1String(":/myspaces/javascript/jquery.min.1.7.js"));
    file.open(QIODevice::ReadOnly);
    jQuery = QString(file.readAll());
    file.close();
    m_splitter->setOrientation(Qt::Vertical);
    setCentralWidget(m_splitter);
    m_splitter->addWidget(Browser);
    m_inspector->setPage(Browser->page());
    m_splitter->addWidget(m_inspector);
    m_inspector->setShown(false);

    // Browser settings
    Browser->settings()->setAttribute(QWebSettings::LocalStorageEnabled,true);
    Browser->setLocale(QLocale::Russian);
    Browser->settings()->setLocalStoragePath(MySettings::dataPath("database"));
    Browser->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled,true);

    toolBar->setMovable(false);
    addToolBar(toolBar);


    /* Navigation buttons */
    connect(forward, SIGNAL(clicked()), Browser, SLOT(forward()));
    forward->setIcon(QIcon(":/data/icons/forward.png"));
    forward->setToolTip(tr("Forward"));

    connect(back, SIGNAL(clicked()), Browser, SLOT(back()));
    back->setIcon(QIcon(":/data/icons/back.png"));
    back->setToolTip(tr("Back"));

    toolBar->addWidget(back);
    toolBar->addWidget(forward);
    toolBar->addWidget(ReloadStop);

    toolBar->addWidget(locationEdit);
    goHomeButton->setIcon(QIcon(":/myspaces/t_icon_home.png"));
    toolBar->addWidget(goHomeButton);
    inspectorButton->setIcon(QIcon(":/data/icons/bug.png"));
    toolBar->addWidget(inspectorButton);
    mainMenuButton->setIcon(QIcon(":/data/icons/settings.png"));
    toolBar->addWidget(mainMenuButton);

    inspectorButton->setCheckable(true);

    CreateMenu();
    mainMenuButton->setCursor(Qt::ArrowCursor);
    mainMenuButton->setPopupMode(QToolButton::InstantPopup);
    mainMenuButton->setFocusPolicy(Qt::ClickFocus);
    connect(mainMenuButton, SIGNAL(clicked()), SLOT(showMenu()));

    mainMenu->setStyle(new QPlastiqueStyle);

    // Connect slots and signals
    connect(Browser, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
    connect(Browser, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(Browser, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(Browser, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
    connect(Browser, SIGNAL(loadStarted()), SLOT(startLoading()));
    connect(Browser, SIGNAL(signalOpenLinkInNewTab(QUrl)),
            this, SLOT(sendOpenNewTab(QUrl)));
    connect(goHomeButton, SIGNAL(clicked()), SLOT(GoHome()));
    connect(mainMenuButton, SIGNAL(clicked()), mainMenu, SLOT(show()));
    connect(m_inspector, SIGNAL(shEvent(bool)),
            this, SLOT(loadInspector(bool)));
    connect(inspectorButton, SIGNAL(clicked(bool)),
            this, SLOT(loadInspector(bool)));
}

myWebView* tabPage::getBrowser()
{
    return Browser;
}

void tabPage::showMenu()
{
    mainMenu->show();
    QPoint pos = mainMenuButton->mapToGlobal(QPoint(0,0));
    int x = pos.x() - mainMenu->width() + mainMenuButton->width();
    int y = pos.y() + mainMenuButton->height();
    mainMenu->move(x,y);
}

void tabPage::loadInspector(bool)
{
    if(!showInspector)
    {
        m_inspector->show();
        showInspector = true;
        inspectorButton->setChecked(true);
    }
    else
    {
        m_inspector->close();
        showInspector = false;
        inspectorButton->setChecked(false);
    }
}

void tabPage::CreateMenu()
{
    mainMenu->addAction(tr("Settings"), this, SLOT(SettingsSlot()));
    mainMenu->addAction(tr("Load development tools"),
                        this, SLOT(loadInspector(bool)));
    mainMenu->addAction(tr("Downloads"), this, SLOT(showDM()));
    mainMenu->addSeparator();
    mainMenu->addAction(tr("About Qt"), qApp, SLOT(aboutQt()));
    mainMenu->addAction(tr("About mySpaces"), this, SLOT(aboutMySpacesSlot()));
    mainMenu->addSeparator();
    mainMenu->addAction(tr("Exit"), this, SLOT(exitApp()));
}

void tabPage::showDM()
{
    mySpaces::showDownloadManager();
}

void tabPage::exitApp()
{
    emit exitApplication();
}

void tabPage::aboutMySpacesSlot()
{
#ifdef BUILD_NUMBER
    QString nbuild = QString(".b%1").arg(BUILD_NUMBER);
#else
    QString nbuild = "";
#endif
    QMessageBox::about(this, tr("About"), tr(
            "Version %1%2"
            "<p>It is client for "
            "social network <a href=\"http://spaces.ru\">spaces.ru</a>.<p>"
            "<p>QtWebKit is based on the Open Source WebKit Project developed at <a href=\"http://webkit.org/\">http://webkit.org/</a>."
                           ).arg(QString(APP_VERSION)).arg(nbuild));
}

void tabPage::SettingsSlot()
{
    emit OpenLinkInNewTab(QUrl("myspaces://settings"));
}

void tabPage::load(const QUrl &url)
{
    Browser->load(url);
}

QUrl tabPage::url()
{
    return Browser->url();
}

void tabPage::setProgress(int p)
{
    progress = p;
}

void tabPage::adjustLocation()
{
    locationEdit->setText(Browser->url().toString());
}

void tabPage::finishLoading(bool)
{
    adjustTitle();

    connect(ReloadStop, SIGNAL(clicked()), Browser, SLOT(reload()));
    ReloadStop->setIcon(QIcon(":/data/icons/reload.png"));
    ReloadStop->setToolTip(tr("Reload"));

    if(Browser->page()->history()->canGoBack())
        back->setEnabled(true);
    else
        back->setEnabled(false);
    if(Browser->page()->history()->canGoForward())
        forward->setEnabled(true);
    else
        forward->setEnabled(false);
}

void tabPage::startLoading()
{
    connect(ReloadStop, SIGNAL(clicked()), Browser, SLOT(stop()));
    ReloadStop->setIcon(QIcon(":/data/icons/stop.png"));
    ReloadStop->setToolTip(tr("Stop"));
}

void tabPage::adjustTitle()
{
    *title = Browser->title();
    emit changeTitle(*title);
}

QString tabPage::getTitle()
{
    return Browser->title();
}

void tabPage::GoHome()
{
    QProcess::startDetached(QApplication::applicationFilePath(), QStringList(),
                            QApplication::applicationDirPath());
    exitApp();
}

void tabPage::addjQuery()
{
    Browser->page()->mainFrame()->evaluateJavaScript(jQuery);
}

tabPage::~tabPage()
{
}
